package com.unionpay.upyzt.net;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.unionpay.upyzt.exception.InvalidRequestException;
import com.unionpay.upyzt.util.MessageDigestUtils;
import com.unionpay.upyzt.util.SHA256Utils;
import lombok.Getter;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;

import static java.util.Objects.requireNonNull;

@Getter
public class HttpContent {

    /**
     * 图片上传最大 5M
     */
    public static final int MAX_UPLOAD_FILE_LENGTH = 5 * 1024 * 1024;

    /**
     * 请求内容
     */
    private final String content;

    /**
     * {@code Content-Type} header 值
     */
    private final String contentType;

    /**
     * 上传文件时，请求体内分隔请求内容的 boundary
     */
    private String boundary;

    private HttpContent(String content, String contentType) {
        this.content = content;
        this.contentType = contentType;
    }

    private HttpContent(String content, String contentType, String boundary) {
        this.content = content;
        this.contentType = contentType;
        this.boundary = boundary;
    }

    public byte[] getContentBytes() {
        return this.content.getBytes(APIResource.CHARSET);
    }

    public static HttpContent buildJSONContent(Map<String, Object> params) {
        requireNonNull(params);

        return new HttpContent(createJSONString(params),
                String.format("application/json; charset=%s", APIResource.CHARSET));
    }

    public static HttpContent buildFileContent(File file) throws InvalidRequestException, IOException {
        requireNonNull(file);
        if (file.length() == 0L) {
            throw new InvalidRequestException("上传文件为空，请更换后重试");
        } else if (file.length() > MAX_UPLOAD_FILE_LENGTH) {
            throw new InvalidRequestException("上传文件大小不能超过 5M，请更换或压缩后重试");
        }

        // byte[] fileContent = Files.readAllBytes(file.toPath());
        Map<String, Object> meta = new HashMap<>();
        meta.put("filename", file.getName());
        meta.put("sha256", MessageDigestUtils.sha256(file));
        String boundary = Long.toHexString(System.currentTimeMillis());

        return new HttpContent(createJSONString(meta),
                String.format("multipart/form-data; boundary=\"%s\"", boundary), boundary);
    }

    /**
     * @param params the parameters
     * @return JSONString
     */
    protected static String createJSONString(Map<String, Object> params) {
        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
        return gson.toJson(params);
    }

}
